package zy.service.shop.kpipk.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import zy.dao.base.emp.EmpRewardDAO;
import zy.dao.base.shop.ShopRewardDAO;
import zy.dao.shop.kpipk.KpiPkDAO;
import zy.entity.PageData;
import zy.entity.PageInfo;
import zy.entity.base.emp.T_Base_EmpGroupList;
import zy.entity.base.emp.T_Base_Emp_Reward;
import zy.entity.base.shop.T_Base_Shop_Reward;
import zy.entity.shop.kpipk.T_Shop_KpiPk;
import zy.entity.shop.kpipk.T_Shop_KpiPkList;
import zy.entity.shop.kpipk.T_Shop_KpiPkReward;
import zy.entity.sys.user.T_Sys_User;
import zy.service.shop.kpipk.KpiPkService;
import zy.util.CommonUtil;
import zy.util.DateUtil;
import zy.util.StringUtil;
import zy.vo.shop.KpiPkVO;

@Service
public class KpiPkServiceImpl implements KpiPkService{
	@Resource
	private KpiPkDAO kpiPkDAO;
	@Resource
	private ShopRewardDAO shopRewardDAO;
	@Resource
	private EmpRewardDAO empRewardDAO;
	
	@Override
	public PageData<T_Shop_KpiPk> page(Map<String, Object> params) {
		Object companyid = params.get(CommonUtil.COMPANYID);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		Integer pageSize = (Integer)params.get(CommonUtil.PAGESIZE);
		Integer pageIndex = (Integer)params.get(CommonUtil.PAGEINDEX);
		
		Integer totalCount = kpiPkDAO.count(params);
		PageInfo pageInfo = new PageInfo(totalCount, pageSize, pageIndex);
		params.put(CommonUtil.START, (pageIndex-1)*pageSize);
		params.put(CommonUtil.END, pageSize);
		
		List<T_Shop_KpiPk> list = kpiPkDAO.list(params);
		PageData<T_Shop_KpiPk> pageData = new PageData<T_Shop_KpiPk>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		return pageData;
	}
	
	@Override
	public List<T_Shop_KpiPk> list4cashier(Map<String, Object> params) {
		Object companyid = params.get(CommonUtil.COMPANYID);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		return kpiPkDAO.list4cashier(params);
	}
	
	@Override
	public T_Shop_KpiPk load(Integer kp_id) {
		return kpiPkDAO.load(kp_id);
	}
	
	@Override
	public Map<String, Object> loadDetail(Map<String, Object> params) {
		String number = StringUtil.trimString(params.get("number"));
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Map<String, Object>> header = kpiPkDAO.loadHeader(number, companyid);
		List<T_Shop_KpiPkList> kpiPkLists = kpiPkDAO.loadDetail(number, companyid);
		//按照总分对表头排序
		final Map<String, Integer> totalScoreMap = new HashMap<String, Integer>();
		for (T_Shop_KpiPkList item : kpiPkLists) {
			if(totalScoreMap.containsKey(item.getKpl_code())){
				totalScoreMap.put(item.getKpl_code(), totalScoreMap.get(item.getKpl_code())+item.getKpl_score());
			}else {
				totalScoreMap.put(item.getKpl_code(), item.getKpl_score());
			}
		}
		Collections.sort(header, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                int c = 0;
                c = totalScoreMap.get(o1.get("kpl_code").toString()) >= totalScoreMap.get(o2.get("kpl_code").toString()) ? 1 : -1;
                return  -c;
            }
        });
		resultMap.put("header", header);
		resultMap.put("details", KpiPkVO.buildDetailJson(kpiPkLists));
		return resultMap;
	}
	
	@Override
	public Map<String, Object> statDetail(Map<String, Object> params) {
		String number = StringUtil.trimString(params.get("number"));
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		List<Map<String, Object>> header = kpiPkDAO.loadHeader(number, companyid);
		T_Shop_KpiPk kpiPk = kpiPkDAO.load(number, companyid);
		params.put("begin", kpiPk.getKp_begin());
		params.put("end", kpiPk.getKp_end()+" 23:59:59");
		params.put("kp_type", kpiPk.getKp_type());
		List<T_Shop_KpiPkList> kpiPkLists = kpiPkDAO.statDetail(params);
		//按照总分对表头排序
		final Map<String, Integer> totalScoreMap = new HashMap<String, Integer>();
		for (T_Shop_KpiPkList item : kpiPkLists) {
			if(totalScoreMap.containsKey(item.getKpl_code())){
				totalScoreMap.put(item.getKpl_code(), totalScoreMap.get(item.getKpl_code())+item.getKpl_score());
			}else {
				totalScoreMap.put(item.getKpl_code(), item.getKpl_score());
			}
		}
		Collections.sort(header, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                int c = 0;
                c = totalScoreMap.get(o1.get("kpl_code").toString()) >= totalScoreMap.get(o2.get("kpl_code").toString()) ? 1 : -1;
                return -c;
            }
        });
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("header", header);
		resultMap.put("details", KpiPkVO.buildDetailJson(kpiPkLists));
		return resultMap;
	}
	
	@Override
	@Transactional
	public void save(T_Shop_KpiPk kpiPk,List<T_Shop_KpiPkList> kpiPkLists, T_Sys_User user) {
		if(StringUtil.isEmpty(kpiPk.getKp_type())){
			throw new IllegalArgumentException("kp_type不能为空");
		}
		if(StringUtil.isEmpty(kpiPk.getKp_begin())){
			throw new IllegalArgumentException("kp_begin不能为空");
		}
		if(StringUtil.isEmpty(kpiPk.getKp_end())){
			throw new IllegalArgumentException("kp_end不能为空");
		}
		if(kpiPk.getKp_score() == null){
			throw new IllegalArgumentException("请输入标准分数");
		}
		if(StringUtil.isEmpty(kpiPk.getReward_codes())){
			throw new IllegalArgumentException("请选择奖励");
		}
		if (kpiPkLists == null || kpiPkLists.size() == 0) {
			throw new IllegalArgumentException("请选择考核范围及KPI指标");
		}
		kpiPk.setKp_state(0);
		kpiPk.setKp_sysdate(DateUtil.getCurrentTime());
		kpiPk.setKp_shop_code(user.getUs_shop_code());
		kpiPk.setKp_us_id(user.getUs_id());
		kpiPk.setCompanyid(user.getCompanyid());
		List<T_Shop_KpiPkReward> kpiPkRewards = new ArrayList<T_Shop_KpiPkReward>();
		String[] rewards = kpiPk.getReward_codes().split(",");
		for (String reward : rewards) {
			T_Shop_KpiPkReward item = new T_Shop_KpiPkReward();
			item.setKpr_rw_code(reward);
			kpiPkRewards.add(item);
		}
		kpiPkDAO.save(kpiPk, kpiPkLists, kpiPkRewards);
	}
	
	@Override
	@Transactional
	public T_Shop_KpiPk complete(T_Shop_KpiPk kpiPk,List<T_Shop_KpiPkList> kpiPkLists) {
		T_Shop_KpiPk checkPk = kpiPkDAO.load(kpiPk.getKp_id());
		if(checkPk == null){
			throw new RuntimeException("PK工具不存在");
		}
		if(!checkPk.getKp_state().equals(0)){
			throw new RuntimeException("PK工具已总结，请勿重复操作");
		}
		checkPk.setKp_state(1);
		checkPk.setKp_summary(checkPk.getKp_summary());
		checkPk.setReward_names(kpiPk.getReward_names());
		List<T_Shop_KpiPkReward> rewards = new ArrayList<T_Shop_KpiPkReward>();
		if(StringUtil.isNotEmpty(kpiPk.getReward_codes())){//修改勋章，重新保存勋章明细
			String[] rwCodes = kpiPk.getReward_codes().split(",");
			for (String rwCode : rwCodes) {
				T_Shop_KpiPkReward reward = new T_Shop_KpiPkReward();
				reward.setKpr_number(checkPk.getKp_number());
				reward.setKpr_rw_code(rwCode);
				reward.setCompanyid(checkPk.getCompanyid());
				rewards.add(reward);
			}
			kpiPkDAO.deleteReward(checkPk.getKp_number(), checkPk.getCompanyid());
			kpiPkDAO.saveReward(rewards);
		}else {//未修改勋章，从数据库中查询
			rewards = kpiPkDAO.listReward(checkPk.getKp_number(), checkPk.getCompanyid());
		}
		
		Map<String, Integer> totalScoreMap = new HashMap<String, Integer>();
		for (T_Shop_KpiPkList item : kpiPkLists) {
			if(!totalScoreMap.containsKey(item.getKpl_code())){
				totalScoreMap.put(item.getKpl_code(), item.getKpl_score());
			}else {
				totalScoreMap.put(item.getKpl_code(), totalScoreMap.get(item.getKpl_code())+item.getKpl_score());
			}
		}
		int maxScore = 0;
		for (String key : totalScoreMap.keySet()) {
			if (totalScoreMap.get(key) > maxScore) {
				maxScore = totalScoreMap.get(key);
			}
		}
		List<String> winnerCodes = new ArrayList<String>();
		if (maxScore > 0 && maxScore >= checkPk.getKp_score()) {
			for (String key : totalScoreMap.keySet()) {
				if(totalScoreMap.get(key).intValue() == maxScore){
					winnerCodes.add(key);
				}
			}
		}
		List<T_Base_Shop_Reward> shopRewards = null;
		List<T_Base_Emp_Reward> empRewards = null;
		if (rewards.size() > 0 && winnerCodes.size() > 0) {
			if(CommonUtil.KPI_ASSESS_TYPE_SHOP.equals(checkPk.getKp_type())){
				shopRewards = new ArrayList<T_Base_Shop_Reward>();
				for (T_Shop_KpiPkReward reward : rewards) {
					for (String winner : winnerCodes) {
						T_Base_Shop_Reward shopReward = new T_Base_Shop_Reward();
						shopReward.setSr_sp_code(winner);
						shopReward.setSr_rw_code(reward.getKpr_rw_code());
						shopReward.setSr_sysdate(DateUtil.getCurrentTime());
						shopReward.setSr_state(0);
						shopReward.setSr_remark("PK工具获得奖励,单据编号["+checkPk.getKp_number()+"]。");
						shopReward.setCompanyid(checkPk.getCompanyid());
						shopRewards.add(shopReward);
					}
				}
			}else if(CommonUtil.KPI_ASSESS_TYPE_EMPGROUP.equals(checkPk.getKp_type())){
				//查询员工组员工，针对员工组发放奖励，是针对员工组内员工发放奖励
				List<T_Base_EmpGroupList> empGroupLists = kpiPkDAO.loadEmpByGroup(winnerCodes, checkPk.getCompanyid());
				Map<String, List<String>> group_emp = new HashMap<String, List<String>>();
				for (T_Base_EmpGroupList item : empGroupLists) {
					if(!group_emp.containsKey(item.getEgl_eg_code())){
						group_emp.put(item.getEgl_eg_code(),new ArrayList<String>());
					}
					group_emp.get(item.getEgl_eg_code()).add(item.getEgl_em_code());
				}
				empRewards = new ArrayList<T_Base_Emp_Reward>();
				for (T_Shop_KpiPkReward reward : rewards) {
					for (String winner : winnerCodes) {
						List<String> emps = group_emp.get(winner);
						if (emps == null || emps.size() == 0) {
							continue;
						}
						for (String em_code : emps) {
							T_Base_Emp_Reward empReward = new T_Base_Emp_Reward();
							empReward.setEr_em_code(em_code);
							empReward.setEr_rw_code(reward.getKpr_rw_code());
							empReward.setEr_sysdate(DateUtil.getCurrentTime());
							empReward.setEr_state(0);
							empReward.setEr_remark("PK工具获得奖励,单据编号["+checkPk.getKp_number()+"]。");
							empReward.setCompanyid(checkPk.getCompanyid());
							empRewards.add(empReward);
						}
					}
				}
			}else if(CommonUtil.KPI_ASSESS_TYPE_EMP.equals(checkPk.getKp_type())){
				empRewards = new ArrayList<T_Base_Emp_Reward>();
				for (T_Shop_KpiPkReward reward : rewards) {
					for (String winner : winnerCodes) {
						T_Base_Emp_Reward empReward = new T_Base_Emp_Reward();
						empReward.setEr_em_code(winner);
						empReward.setEr_rw_code(reward.getKpr_rw_code());
						empReward.setEr_sysdate(DateUtil.getCurrentTime());
						empReward.setEr_state(0);
						empReward.setEr_remark("PK工具获得奖励,单据编号["+checkPk.getKp_number()+"]。");
						empReward.setCompanyid(checkPk.getCompanyid());
						empRewards.add(empReward);
					}
				}
			}
		}
		
		kpiPkDAO.complete(checkPk);
		kpiPkDAO.completeDetail(kpiPkLists);
		if (shopRewards != null && shopRewards.size() > 0) {
			shopRewardDAO.save(shopRewards);
		}
		if (empRewards != null && empRewards.size() > 0) {
			empRewardDAO.save(empRewards);
		}
		return checkPk;
	}
	
	@Override
	@Transactional
	public void del(Integer kp_id) {
		T_Shop_KpiPk kpiPk = kpiPkDAO.load(kp_id);
		if(kpiPk == null){
			throw new RuntimeException("PK工具不存在");
		}
		if(!kpiPk.getKp_state().equals(0)){
			throw new RuntimeException("PK工具已总结，不能删除");
		}
		kpiPkDAO.del(kpiPk.getKp_number(), kpiPk.getCompanyid());
	}
	
}
